<?php

declare(strict_types=1);

namespace app\agent\controller;

use app\admin\service\AgentRefund;
use app\Request;
use app\agent\validate\Refund as RefundValidate;

/** @apiDefine Admin2_0_agent Agent2.0 */
class Refund extends Controller
{
    /**
     * @api {POST} /agent/refund/apply 申请退款
     * @apiName agentRefundApply 代理商退款申请，目前为了流水的完整，该退款针对已经提交到后台的
     * @apiDescription 代理商退款申请
     * @apiParam {Number} amount 退款金额
     * @apiParam {String} alipay 支付宝账号
     * @apiParam {String} wechat 订单号
     * @apiParam {String} mobile 手机号
     * @apiGroup Admin2_0_agent
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function apply(Request $request)
    {
        $data = input('post.');
        $validate = new RefundValidate();
        if (empty($data['type']) || !in_array($data['type'], [1, 2])) {
            return fail('退款方式有误，请刷新重试');
        }
        $scene = 'alipay';
        if ($data['type'] == 2) {
            $scene = 'bank';
        }

        if (!$validate->scene($scene)->check($data)) {
            return fail($validate->getError());
        }

        $data['amount'] = yuan2fen($data['amount']);
        $res = (new AgentRefund())->apply($this->agent['id'], $data);
        if ($res['code']) {
            return fail($res['msg']);
        }

        return success('申请成功');
    }

    /**
     * @api {POST} /agent/refund/cancel 撤销退款申请
     * @apiDescription 撤销退款申请
     * @apiName agentRefundCancel
     * @apiGroup Admin2_0_agent
     * @apiParam {Number} id
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function cancel()
    {
        if (!$this->request->param('id')) {
            return fail('缺少必要参数');
        }
        $res = invoke(AgentRefund::class)->cancelByBalanceLogId($this->agent['id'], $this->request->param('id'));
        if ($res['code']) {
            return fail($res['msg']);
        }

        return success();
    }
}
